﻿// Original author contact info: Owen Emlen (owene_1998@yahoo.com)
// Note: other individuals may also have contributed to this code
// Project hosted on CodePlex.com as of 1/10/2009 at http://www.codeplex.com/EmlenMud
using System;
using System.Reflection;
using BrainTechLLC.ThreadSafeObjects;
using LinFu.AOP.Interfaces;

namespace BrainTechLLC
{
	[Serializable]
	public class RestrictPropertyChangeAttribute : Attribute, IReadableAttribute
	{
		public readonly static string DefaultRestrictMethod = "RestrictPropertyChange";

		public string RestrictMethodName { get; set; }
		public bool ThrowOnException { get; set; }
		public object Value { get { return RestrictMethodName; } }

		public RestrictPropertyChangeAttribute() { RestrictMethodName = DefaultRestrictMethod; }
		public RestrictPropertyChangeAttribute(string restrictMethod) { RestrictMethodName = restrictMethod; }
		public RestrictPropertyChangeAttribute(string restrictMethod, bool throwOnException) : this(restrictMethod) { ThrowOnException = throwOnException; }

		public MethodInfo GetMethod(Type t)
		{
			return Lookups.GeneralLookup.Get(RestrictMethodName, v => t.GetMethod(RestrictMethodName));
		}

		public Exception IsRestricted(object item, Type t, string propertyName, object oldVal, object newVal, IInvocationContext context)
		{			
			return GetMethod(t).InvokeIfNotNull(item, propertyName, oldVal, newVal, context) as Exception;
		}
	}
}

